class Watermark {
  constructor(typeConfig = {}) {
    if (typeof typeConfig !== 'object') typeConfig = {}
    typeConfig = Object.assign({ width: 250, height: 250, font: '14px Vedana', color: 'rgba(0,0,0, .2)', textAlign: 'left' }, typeConfig)
    this.width = typeConfig.width
    this.height = typeConfig.height
    this.font = typeConfig.font
    this.color = typeConfig.color
    this.textAlign = typeConfig.textAlign
  }
  createCanvas(title, subTitle) {
    const id = '1684910106891'
    if (document.getElementById(id) !== null) {
      // document.body.removeChild(document.getElementById(id))
    }
    // 创建一个画布
    const can = document.createElement('canvas')
    // 设置画布的长宽
    can.width = this.width
    can.height = this.height

    const cans = can.getContext('2d')
    // 旋转角度
    cans.rotate(-30 * Math.PI / 180)
    cans.font = this.font
    // 设置填充绘画的颜色、渐变或者模式
    cans.fillStyle = this.color
    // 设置文本内容的当前对齐方式
    cans.textAlign = this.textAlign
    // 设置在绘制文本时使用的当前文本基线
    cans.textBaseline = 'Middle'
    // 在画布上绘制填色的文本（输出的文本，开始绘制文本的X坐标位置，开始绘制文本的Y坐标位置）
    cans.fillText(title, can.width / 8, can.height / 2)
    subTitle && cans.fillText(subTitle, can.width / 8, can.height / 2 + 22)
    let div = document.getElementById(id)
    let flag = false
    if (!div) {
      flag = true
      div = document.createElement('div')
      div.id = id
    }
    div.style.pointerEvents = 'none'
    div.style.zIndex = '100000'
    div.style.width = '100%'
    div.style.height = '100%'
    div.style.position = 'absolute'
    div.style.top = '0px'
    div.style.left = '0px'
    div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
    if (flag) {
      div.style.top = '30px'
      div.style.left = '0px'
      div.style.position = 'fixed'
      div.style.width = document.documentElement.clientWidth + 'px'
      div.style.height = document.documentElement.clientHeight + 'px'
      document.body.appendChild(div)
      flag = false
    }
    return id
  }
  init(...str) {
    let id = this.createCanvas(...str)
    this.interval = setInterval(() => {
      if (document.getElementById(id) === null) {
        id = this.createCanvas(...str)
      }
    }, 500)
    window.onresize = () => {
      this.createCanvas(...str)
    }
  }
  destroy() {
    clearInterval(this.interval)
    this.interval = null
    window.onresize = null
  }
}

export default Watermark
